package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.JsonResult;

import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    // 处理新增请求 http://localhost/role/saveOrUpdate.do POST  name: adf sn: asdf
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids) {
        if (role.getId() != null) { // 修改
            roleService.update(role,ids);
        }else { // 新增
            roleService.save(role,ids);
        }
        return "redirect:/role/list.do";
    }

    // 处理去新增请求 http://localhost/role/input.do
    @RequestMapping("/input")
    public String input(Long id, Model model){
        model.addAttribute("permissions",permissionService.listALL());

        // 若传 id 值，表示是去修改，那就要去查询被修改的部门对象，存在模型中
        if (id != null) {
            model.addAttribute("role", roleService.get(id));
        }
        return "role/input"; // /WEB-INF/views/role/input.ftl
    }

    
    // 处理删除部门请求 http://localhost/role/delete.do?id=1
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) { // 传id值就删除对应的部门数据
                roleService.delete(id);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败，请联系管理员");
        }

    }


    // 处理分页查询部门的请求
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        // 分页查询部门数据，存在模型
        model.addAttribute("pageInfo", roleService.query(qo));
        // 找视图
        return "role/list"; // /WEB-INF/views/role/potentialList.ftl
    }

}
